<?php
namespace app\api_wp_v01\controller;

class RecycleOrder extends ApiWechatProgram {
	
	public function get_listing(){
		
		$parameter = \think\Request::instance()->post();
		$judge_1 = array_key_exists('target', $parameter) && is_string($parameter['target']) && (('all' === $parameter['target']) || in_array($parameter['target'], \app\common\model\RecycleOrderModel::$status_alias));
		$judge_2 = array_key_exists('page', $parameter) && is_integer($parameter['page']) && (0 < $parameter['page']);
		if(!$judge_1 || !$judge_2){
			return $this->disposeJson(1, '参数校验失败');
		};
		
		$where = array();
		if('all' !== $parameter['target']){
			$status_alias = array_flip(\app\common\model\RecycleOrderModel::$status_alias);
			$where['recycle_order.status'] = $status_alias[$parameter['target']];
		};
		
		$field = array(
			'`recycle_order`.`id`', '`recycle_order`.`action_date`', '`recycle_order`.`action_time`',
			'`recycle_order`.`address`', '`recycle_order`.`address_describe`',
			'`region`.`name_full` AS `region_name`'
		);
		$order_select = \app\common\model\RecycleOrderModel::field($field)
			->join('region', '`region`.`id` = `recycle_order`.`region_district`', 'LEFT')
			->where('recycle_order.subscriber_id', $this->subscriber_id)
			->where($where)
			->order('recycle_order.id DESC')
			->limit(10)->page($parameter['page'])
			->select();
		if(0 === count($order_select)){
			return $this->disposeJson(1, '没有更多的数据了');
		};
		
		$order_list = array();
		foreach($order_select as $RecycleOrder){
			$order = array(
				'id' => $RecycleOrder->id,
				'action_date' => date('Y-m-d', $RecycleOrder->action_date),
				'action_time' => $RecycleOrder->action_time,
				'region_name' => $RecycleOrder->region_name,
				'address' => $RecycleOrder->address,
			);
			$order_list[] = $order;
		};
		
		return $this->disposeJson(0, '', array(
			'order_list' => $order_list,
		));
	}
	
	public function get_detail() {
		
		$parameter = \think\Request::instance()->post();
		$judge_1 = array_key_exists('id', $parameter) && is_integer($parameter['id']) && (0 < $parameter['id']);
		if(!$judge_1){
			return $this->disposeJson(1, '参数校验失败');
		};
		
		$RecycleOrderModel = \app\common\model\RecycleOrderModel::get($parameter['id']);
		if(null === $RecycleOrderModel){
			return $this->disposeJson(1, '目标不存在');
		}else if($this->subscriber_id !== $RecycleOrderModel->subscriber_id){
			return $this->disposeJson(1, '该订单不属于你');
		};
		
		$data = array(
			'number' => $RecycleOrderModel->identifier,
			'genre' => $RecycleOrderModel->genre,
			'genre_name' => $RecycleOrderModel->getGenreName(),
			'action_date' => date('Y-m-d', $RecycleOrderModel->action_date),
			'action_time' => $RecycleOrderModel->action_time,
			'remark' => $RecycleOrderModel->remark,
			'liaison_name' => $RecycleOrderModel->liaison_name,
			'liaison_phone' => $RecycleOrderModel->liaison_phone,
			'region_name' => '',
			'address' => $RecycleOrderModel->address,
			'address_describe' => $RecycleOrderModel->address_describe,
			'create_time' => date('Y-m-d H:i:s', $RecycleOrderModel->create_time),
			'status' => $RecycleOrderModel->status,
			'status_name' => $RecycleOrderModel->getStatusName(),
			'can_cancel' => false,
			'cancel_time' => '',
			'cancel_cause' => '',
		);
		
		// 获取地区
		$RegionModel = \app\common\model\RegionModel::get($RecycleOrderModel->region_district);
		if(null === $RegionModel){
			return $this->disposeJson(1, '获取地区信息失败');
		};
		$data['region_name'] = $RegionModel->name_full;
		
		// 生成二维码
		$QrCode = new \CodeItNow\BarcodeBundle\Utils\QrCode($RecycleOrderModel->id);
		$QrCode->setPadding(0);
		$QrCode->setSize(130);
		$data['qrcode_base64'] = 'data:'.$QrCode->getContentType().';base64,'.$QrCode->generate();
		
		// 判断订单状态
		switch($RecycleOrderModel->status){
			case 0 :
				$data['cancel_time'] = date('Y-m-d H:i:s', $RecycleOrderModel->cancel_time);
				$data['cancel_cause'] = $RecycleOrderModel->cancel_cause;
				break;
				
			case 1 :
				$data['can_cancel'] = true;
				break;
		};
		
		// 获取员工信息
		if(1 < $RecycleOrderModel->status){
			$StaffModel = \app\common\model\StaffModel::get($RecycleOrderModel->staff_id);
			if(null === $StaffModel){
				return $this->disposeJson(1, '对应的员工未找到');
			};
			$data['staff_realname'] = $StaffModel->realname;
			$data['staff_phone'] = $StaffModel->phone;
		};
		
		return $this->disposeJson(0, '', $data);
	}
	
	/**
	 * 预约回收
	 */
	public function appoint() {
		
		$recycle_action_time = \think\Config::get('recycle_action_time');
		
		$parameter = \think\Request::instance()->post();
		$judge_1 = array_key_exists('type', $parameter) && is_integer($parameter['type']) && in_array($parameter['type'], array_keys(\app\common\model\RecycleOrderModel::$genre));
		$judge_2 = array_key_exists('address', $parameter) && is_integer($parameter['address']) && (0 < $parameter['address']);
		$judge_3 = array_key_exists('date', $parameter) && is_string($parameter['date']) && (1 === preg_match('/\d{4}-\d{2}-\d{2}/', $parameter['date']));
		$judge_4 = array_key_exists('time', $parameter) && is_integer($parameter['time']) && in_array($parameter['time'], array_keys($recycle_action_time));
		$judge_5 = array_key_exists('rate', $parameter) && is_integer($parameter['rate']);
		$judge_6 = array_key_exists('remark', $parameter) && is_string($parameter['remark']);
		if(!$judge_1 || !$judge_2 || !$judge_3 || !$judge_4 || !$judge_5 || !$judge_6){
			return $this->disposeJson(1, '参数校验失败');
		};
		
		if(2 === $parameter['type']){
			$judge_1 = in_array($parameter['rate'], array_keys(\app\common\model\RecycleOrderLongModel::$frequency));
			if(!$judge_1){
				return $this->disposeJson(1, '长期预约参数校验失败');
			};
		};
		
		// 校验日期
		$parameter['date'] = strtotime($parameter['date']);
		if(!is_integer($parameter['date']) || (0 >= $parameter['date'])){
			return $this->disposeJson(1, '传入的日期不正确');
		};
		
		// 获取用户信息
		$SubscriberModel = \app\common\model\SubscriberModel::get($this->subscriber_id);
		if(null === $SubscriberModel){
			return $this->disposeJson(1, '用户信息不存在');
		};
		
		// 校验地址
		$RecycleAddressModel = \app\common\model\RecycleAddressModel::get($parameter['address']);
		if((null === $RecycleAddressModel) || (0 !== $RecycleAddressModel->is_del)){
			return $this->disposeJson(1, '选中的地址不存在，请退出后重试');
		}else if($this->subscriber_id !== $RecycleAddressModel->subscriber_id){
			return $this->disposeJson(1, '该地址不是你绑定的');
		};
		
		// 生成订单编号
		$time = time();
		$microtime = microtime();
		$identifier_content = $time . substr($microtime, 2, 6) . strval(mt_rand(10, 99));
		
		\app\common\model\Model::startTrans();
		try{
			
			// 保存长期订单
			if(2 === $parameter['type']){
				$RecycleOrderLongModel = new \app\common\model\RecycleOrderLongModel();
				$RecycleOrderLongModel->identifier = \think\Config::get('order_identifier_suffix.recycle_long') . $identifier_content;
				$RecycleOrderLongModel->subscriber_id = $SubscriberModel->id;
				$RecycleOrderLongModel->frequency = $parameter['rate'];
				$RecycleOrderLongModel->action_date = $parameter['date'];
				$RecycleOrderLongModel->action_time = $recycle_action_time[$parameter['time']];
				$RecycleOrderLongModel->remark = $parameter['remark'];
				$RecycleOrderLongModel->liaison_name = $RecycleAddressModel->liaison_name;
				$RecycleOrderLongModel->liaison_phone = $RecycleAddressModel->liaison_phone;
				$RecycleOrderLongModel->position_lat = $RecycleAddressModel->position_lat;
				$RecycleOrderLongModel->position_lng = $RecycleAddressModel->position_lng;
				$RecycleOrderLongModel->region_province = $RecycleAddressModel->region_province;
				$RecycleOrderLongModel->region_city = $RecycleAddressModel->region_city;
				$RecycleOrderLongModel->region_district = $RecycleAddressModel->region_district;
				$RecycleOrderLongModel->address = $RecycleAddressModel->address;
				$RecycleOrderLongModel->address_describe = $RecycleAddressModel->address_describe;
				$RecycleOrderLongModel->status = 1;
				$RecycleOrderLongModel->create_time = $time;
				$result = $RecycleOrderLongModel->save();
				if(false == $result){
					return $this->disposeJson(1, '保存长期订单失败');
				};
				
				$parent_id = $RecycleOrderLongModel->id;
				$identifier_fuffix = \think\Config::get('order_identifier_suffix.recycle_long_child');
			}else{
				$parent_id = 0;
				$identifier_fuffix = \think\Config::get('order_identifier_suffix.recycle_once');
			};
			
			// 保存订单数据
			$RecycleOrderModel = new \app\common\model\RecycleOrderModel();
			$RecycleOrderModel->identifier = $identifier_fuffix . $identifier_content;
			$RecycleOrderModel->subscriber_id = $SubscriberModel->id;
			$RecycleOrderModel->genre = $parameter['type'];
			$RecycleOrderModel->parent_id = $parent_id;
			$RecycleOrderModel->action_date = $parameter['date'];
			$RecycleOrderModel->action_time = $recycle_action_time[$parameter['time']];
			$RecycleOrderModel->remark = $parameter['remark'];
			$RecycleOrderModel->liaison_name = $RecycleAddressModel->liaison_name;
			$RecycleOrderModel->liaison_phone = $RecycleAddressModel->liaison_phone;
			$RecycleOrderModel->position_lat = $RecycleAddressModel->position_lat;
			$RecycleOrderModel->position_lng = $RecycleAddressModel->position_lng;
			$RecycleOrderModel->region_province = $RecycleAddressModel->region_province;
			$RecycleOrderModel->region_city = $RecycleAddressModel->region_city;
			$RecycleOrderModel->region_district = $RecycleAddressModel->region_district;
			$RecycleOrderModel->address = $RecycleAddressModel->address;
			$RecycleOrderModel->address_describe = $RecycleAddressModel->address_describe;
			$RecycleOrderModel->status = 1;
			$RecycleOrderModel->create_time = $time;
			$result = $RecycleOrderModel->save();
			if(false == $result){
				return $this->disposeJson(1, '保存数据失败');
			};
			
			\app\common\model\Model::commit();
			
		}catch(\Exception $error){
			
			\app\common\model\Model::rollback();
			$message = is_string($error->getMessage()) ? $error->getMessage() : json_encode($error->getMessage());
			return $this->disposeJson(1, $message);
		};
		
		return $this->disposeJson(0, '预约成功');
	}
	
	public function cancel() {
		
		$parameter = \think\Request::instance()->post();
		$judge_1 = array_key_exists('id', $parameter) && is_integer($parameter['id']) && (0 < $parameter['id']);
		if(!$judge_1){
			return $this->disposeJson(1, '参数校验失败');
		};
		
		$RecycleOrderModel = \app\common\model\RecycleOrderModel::get($parameter['id']);
		if(null === $RecycleOrderModel){
			return $this->disposeJson(1, '目标未找到');
		}else if(1 !== $RecycleOrderModel->status){
			return $this->disposeJson(1, '目标状态不正确');
		};
		
		$time = time();
		$result = \app\common\model\RecycleOrderModel::where('id', $RecycleOrderModel->id)->where('status', 1)
			->update([
				'status' => 0,
				'cancel_time' => $time,
				'cancel_cause' => '用户主动取消',
			]);
		if(1 !== $result){
			return $this->disposeJson(1, '修改订单状态失败');
		};
		
		return $this->disposeJson(0, '操作成功');
		
	}
	
}